import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:oktoast/oktoast.dart';
import 'github_repo.dart';
import 'user_repo.dart';
import '../utils/sp_utils.dart';

const _keyUserName = "username";
const _keyPassword = "password";
const _keyLoginState = "loginState";

class LoginRepo with Repo {
  GithubRepo repo = GithubRepo();
  var userRepo = UserRepo();

  final _storage = FlutterSecureStorage();

  Future<bool> login(String username, String password, bool saveLogin) async {
    if (username == null || username.isEmpty) {
      showToast("用户名不能为空");
      return false;
    }
    if (password == null || password.isEmpty) {
      showToast("密码不能为空");
      return false;
    }
    repo.setUserName(username, password);
    try {
      var currentUser = await client.users.getCurrentUser();
      userRepo.currentUser = currentUser;
      if (saveLogin) {
        _saveLoginInfo(username, password);
      } else {
        _saveUserName(username);
        clearSavedPassword();
      }
      saveLoginState = saveLogin;
      return true;
    } catch (e) {
      showToast("登录失败");
      return false;
    }
  }

  bool get isLogin => userRepo.isLogin;

  void logout() {
    userRepo.logout();
  }

  void _saveLoginInfo(String username, String password) {
    _saveUserName(username);
    _storage.write(key: _keyPassword, value: password);
  }

  Future<String> loadSavedUsername() async {
    return _storage.read(key: _keyUserName);
  }

  Future<String> loadSavedPassword() async {
    return _storage.read(key: _keyPassword);
  }

  void clearSavedPassword() {
    _storage.delete(key: _keyPassword);
  }

  void _saveUserName(String username) {
    _storage.write(key: _keyUserName, value: username);
  }

  set saveLoginState(bool saveLoginState) =>
      sp.setBool(_keyLoginState, saveLoginState);

  bool get saveLoginState => sp.getBool(_keyLoginState) ?? true;
}
